package com.zhanjiangyifang.shop.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhanjiangyifang.shop.R;

import java.util.ArrayList;
import java.util.List;

/**
 *  空页面 错误页面 数据加载中 展示
 *
 * Created by rui on 2016/4/5.
 */
public class StatueLayout extends LinearLayout {


    private ViewGroup mLoadingView;
    private ViewGroup mEmptyView;
    private ViewGroup mErrorView;

    private TextView mLoadingMessageView;
    private TextView mEmptyMessageView;
    private TextView mErrorMessageView;

    private TextView mErrorViewButton;


    private RelativeLayout mStatueRelativeLayout;

    private LayoutInflater mInflater;
    private boolean mViewsAdded;

    private OnClickListener mErrorButtonClickListener;

    private List<View> childViews;
    private List<Integer> childVisibility;//子View显示状态

    /**
     * 初始状态为 加载
     */
    private int mStatueType = TYPE_LOADING;

    /**
     * 加载
     */
    public final static int TYPE_LOADING = 1;
    /**
     * 空状态
     */
    public final static int TYPE_EMPTY = 2;
    /**
     * 错误
     */
    public final static int TYPE_ERROR = 3;

    /**
     * 初始图片资源
     */
    private int mErrorDrawable = R.mipmap.icon_error;
    private int mEmptyDrawable = R.mipmap.icon_empty;
    private int mLoadingDrawable = R.mipmap.icon_loading;

    private String mErrorMessage = "页面加载出错，请检查网络设置。";
    private String mEmptyMessage = "啥也没有";
    private String mLoadingMessage = "请等一等啦";


    public StatueLayout(Context context) {
        super(context);
        init();
    }

    public StatueLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public StatueLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        childViews = new ArrayList<>();
        childVisibility=new ArrayList<>();
        mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    /**
     * 展示加载中
     * @param resId
     * @param text
     */
    public void showLoading(int resId, String text) {
        this.mLoadingDrawable = resId;
        this.mLoadingMessage = text;
        showLoading();
    }

    public void showLoading() {
        this.mStatueType = TYPE_LOADING;
        showChildView();//初始化子view显示状态
        getChildViews();
        hideChildView();
        changeStatueView();
    }

    /**
     * 展示错误信息
     * @param resId
     * @param text
     * @param errorButtonClickListener
     */
    public void showError(int resId, String text, OnClickListener errorButtonClickListener) {
        this.mErrorButtonClickListener = errorButtonClickListener;
        showError(resId, text);
    }

    public void showError(int resId, String text) {
        this.mErrorDrawable = resId;
        this.mErrorMessage = text;
        showError();
    }

    public void showError( OnClickListener errorButtonClickListener) {
        this.mErrorButtonClickListener = errorButtonClickListener;
        showError();
    }

    public void showError() {
        this.mStatueType = TYPE_ERROR;
        showChildView();//初始化子view显示状态
        getChildViews();
        hideChildView();
        changeStatueView();
    }

    /**
     * 展示空信息
     * @param resId
     * @param text
     */
    public void showEmpty(int resId, String text) {
        this.mEmptyDrawable = resId;
        this.mEmptyMessage = text;
        showEmpty();
    }

    public void showEmpty(String text) {
        this.mEmptyMessage = text;
        showEmpty();
    }

    public void showEmpty() {
        this.mStatueType = TYPE_EMPTY;
        showChildView();//初始化子view显示状态
        getChildViews();
        hideChildView();
        changeStatueView();
    }

    /**
     * 隐藏EmptyLayout
     */
    public void hide() {
        hideStatueView();
        showChildView();
    }

    private void changeStatueView() {
        setDefaultValues();
        if (mStatueRelativeLayout != null && mStatueRelativeLayout.getVisibility() == GONE) {
            mStatueRelativeLayout.setVisibility(VISIBLE);
        }

        View loadingAnimationView = findViewById(R.id.imageViewLoading);
        switch (mStatueType) {
            case TYPE_EMPTY:
                mEmptyMessageView.setText(mEmptyMessage);
                setTopDrawables(mEmptyMessageView, mEmptyDrawable);
                if (mEmptyView != null) mEmptyView.setVisibility(View.VISIBLE);
                if (mErrorView != null) mErrorView.setVisibility(View.GONE);
                if (mLoadingView != null) {
                    mLoadingView.setVisibility(View.GONE);
                    if (loadingAnimationView != null && loadingAnimationView.getAnimation() != null)
                        loadingAnimationView.getAnimation().cancel();
                }
                break;
            case TYPE_ERROR:
                mErrorMessageView.setText(mErrorMessage);
                setTopDrawables(mErrorMessageView, mErrorDrawable);
                if (mErrorButtonClickListener != null) {
                    mErrorViewButton.setVisibility(VISIBLE);
                    mErrorViewButton.setOnClickListener(mErrorButtonClickListener);
                } else {
                    mErrorViewButton.setVisibility(GONE);
                }
                if (mEmptyView != null) mEmptyView.setVisibility(View.GONE);
                if (mErrorView != null) mErrorView.setVisibility(View.VISIBLE);
                if (mLoadingView != null) {
                    mLoadingView.setVisibility(View.GONE);
                    if (loadingAnimationView != null && loadingAnimationView.getAnimation() != null)
                        loadingAnimationView.getAnimation().cancel();
                }
                break;
            case TYPE_LOADING:
                mLoadingMessageView.setText(mLoadingMessage);
                if (mEmptyView != null) mEmptyView.setVisibility(View.GONE);
                if (mErrorView != null) mErrorView.setVisibility(View.GONE);
                if (mLoadingView != null) {
                    mLoadingView.setVisibility(View.VISIBLE);
                    if (loadingAnimationView != null) {
                        loadingAnimationView.startAnimation(getRotateAnimation());
                    }
                }
                break;
            default:
                break;
        }
    }

    private void setDefaultValues() {
        if (!mViewsAdded) {
            if (mLoadingView == null) {
                mLoadingView = (ViewGroup) mInflater.inflate(R.layout.view_loading, null);
                mLoadingMessageView = mLoadingView.findViewById(R.id.textViewMessage);
            }
            if (mEmptyView == null) {
                mEmptyView = (ViewGroup) mInflater.inflate(R.layout.view_empty, null);
                mEmptyMessageView = mEmptyView.findViewById(R.id.textViewMessage);
            }
            if (mErrorView == null) {
                mErrorView = (ViewGroup) mInflater.inflate(R.layout.view_error, null);
                mErrorViewButton = mErrorView.findViewById(R.id.buttonError);
                mErrorMessageView = mErrorView.findViewById(R.id.textViewMessage);
            }

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            lp.addRule(RelativeLayout.CENTER_IN_PARENT);
            mStatueRelativeLayout = new RelativeLayout(getContext());
            mStatueRelativeLayout.setGravity(Gravity.CENTER);
            mStatueRelativeLayout.setLayoutParams(lp);
            mStatueRelativeLayout.addView(mEmptyView);
            mStatueRelativeLayout.addView(mLoadingView);
            mStatueRelativeLayout.addView(mErrorView);
            addView(mStatueRelativeLayout);
            mViewsAdded = true;
        }
    }

    private void getChildViews() {
        int childCount = getChildCount();
        View view;
        for (int i = 0; i < childCount; i++) {
            view = getChildAt(i);
            if (isStatueView(view)) {
                continue;
            }
            childViews.add(view);
            childVisibility.add(view.getVisibility());
        }
    }

    private void hideChildView() {
        for (View view : childViews) {
            if (isStatueView(view)) {
                continue;
            }
            view.setVisibility(GONE);
        }
    }

    private void showChildView() {
        for (int i=0;i<childViews.size();i++) {
            if (isStatueView(childViews.get(i))) {
                continue;
            }
            childViews.get(i).setVisibility(childVisibility.get(i));
        }
    }

    /**
     * 隐藏EmptyView
     */
    private void hideStatueView() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(GONE);
        }

        if (mEmptyView != null) {
            mEmptyView.setVisibility(GONE);
        }

        if (mErrorView != null) {
            mErrorView.setVisibility(GONE);
        }

        if (mStatueRelativeLayout != null) {
            mStatueRelativeLayout.setVisibility(GONE);
        }
    }

    /**
     * 判断view 对象是否是StatueView
     * @param view
     * @return
     */
    private boolean isStatueView(View view) {
        if ((view == null || mStatueRelativeLayout == view || view == mLoadingView || view == mEmptyView || view == mErrorView)) {
            return true;
        }
        return false;
    }

    private void setTopDrawables(TextView textView, int resId) {
        Drawable drawable = getResources().getDrawable(resId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
        textView.setCompoundDrawables(null, drawable, null, null);
    }

    private static Animation getRotateAnimation() {
        final RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, .5f,
                Animation.RELATIVE_TO_SELF, .5f);
        rotateAnimation.setDuration(1500);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        rotateAnimation.setRepeatCount(Animation.INFINITE);
        return rotateAnimation;
    }
}